/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.config;

import cc.jweb.adai.handler.LayuiAdminRouteHandler;
import cc.jweb.adai.interceptor.SyslogInterceptor;
import cc.jweb.adai.plugin.monitor.TestWebMonitorPlugin;
import cc.jweb.adai.web.system.generator.service.CodeGenerator;
import cc.jweb.adai.web.websocket.service.LogWebSocketService;
import com.jfinal.config.Constants;
import com.jfinal.config.Interceptors;
import com.jfinal.config.Routes;
import com.jfinal.plugin.IPlugin;
import io.jboot.aop.jfinal.JfinalHandlers;
import io.jboot.aop.jfinal.JfinalPlugins;
import io.jboot.core.listener.JbootAppListenerBase;

import javax.websocket.Session;
import java.util.Map;

/**
 * JWeb配置文件
 */
public class JwebAppConfig extends JbootAppListenerBase {


    @Override
    public void onInit() {
        CodeGenerator.init();
    }

    /**
     * 供Shiro插件使用。
     */
    Routes routes;

    @Override
    public void onRouteConfig(Routes me) {
        this.routes = me;
    }


    @Override
    public void onInterceptorConfig(Interceptors me) {
        me.addGlobalActionInterceptor(new SyslogInterceptor());
    }


    @Override
    public void onHandlerConfig(JfinalHandlers handlers) {
        handlers.add(new LayuiAdminRouteHandler());
    }

    @Override
    public void onConstantConfig(Constants constants) {
    }

    @Override
    public void onPluginConfig(JfinalPlugins plugins) {
        plugins.add(new TestWebMonitorPlugin());
        plugins.add(new IPlugin() {
            @Override
            public boolean start() {
                return true;
            }

            @Override
            public boolean stop() {
                Map<String, Session> sessionCache = LogWebSocketService.getSessionCache();
                for (String key : sessionCache.keySet()) {
                    Session session = sessionCache.get(key);
                    if (session.isOpen()) {
                        try {
                            session.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                return true;
            }
        });
    }
}
